package com.boat.starter.springdoc.filter;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import com.boat.starter.springdoc.props.DocProperties;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理v3不支持定制basePath问题
 * 
 * @author 周江
 *
 */

@Slf4j
@Aspect
public class OpenapiJsonInterceptor {

	private final String EXECUTE_EXPR = "execution(* org.springdoc.webmvc.api.OpenApiWebMvcResource.openapiJson(..)) or execution(* org.springdoc.webmvc.api.MultipleOpenApiWebMvcResource.openapiJson(..))";

	private DocProperties docProperties;

	public OpenapiJsonInterceptor(DocProperties docProperties) {
		super();
		this.docProperties = docProperties;
	}

	@Around(EXECUTE_EXPR)
	public Object process(ProceedingJoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
		// 2.调用业务方法
		String response = null;
		try {
			response = (String) joinPoint.proceed(args);
			response = appendBasePath(response);
		} catch (Throwable ex) {
			throw new RuntimeException(ex);
		}

		return response;
	}

	private String appendBasePath(String response) {
		if (StrUtil.isBlank(docProperties.getSpringdoc().getBasePath())
				|| "/".equals(docProperties.getSpringdoc().getBasePath())) {
			return response;
		}

		JSONObject json = JSONUtil.parseObj(response);
		json.set("basePath", docProperties.getSpringdoc().getBasePath());
		return json.toString();
	}

}
